package cc.chinagps.gateway.client.session;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Data
public class UnitClientSession extends AbstractSession {

    public UnitClientSession() {
        super();
    }

    public UnitClientSession(ChannelHandlerContext ctx) {
        super(SessionType.SUPERIOR, ctx);
        String keepAliveTime = "300000";// TODO get from config file
        if (keepAliveTime != null) {
            setMaxKeepAliveTime(Integer.valueOf(keepAliveTime));
        }
    }

    @Override
    public boolean sendData(byte[] data) throws Exception {
        if (connected) {
            setLastActiveTime(System.currentTimeMillis());
            synchronized (ctx) {
                ByteBuf buf = Unpooled.copiedBuffer(data);
                ctx.writeAndFlush(buf);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean sendData(ByteBuf data) throws Exception {
        if (connected) {
            setLastActiveTime(System.currentTimeMillis());
            synchronized (ctx) {
                ctx.writeAndFlush(data);
            }
            return true;
        }
        return false;
    }

    @Override
    public void close() {
        ctx.channel().close();
    }

    @Override
    public String toString() {
        return "UnitClientSession{" +
                "sessionId=" + sessionId +
                ", sessionType=" + sessionType +
                ", protocolType=" + protocolType +
                ", remoteSocketAddress=" + remoteSocketAddress +
                ", localSocketAddress=" + localSocketAddress +
                ", connected=" + connected +
                ", authed=" + authed +
                ", closing=" + closing +
                ", lastActiveTime=" + lastActiveTime +
                ", createTime=" + createTime +
                '}';
    }
}
